/* A layout manager that uses a odt file to set named bounds */
package it.tukano.odt;

import it.tukano.collections.HashMapExt;
import it.tukano.collections.MapExt;
import it.tukano.io.FileExt;
import it.tukano.io.Zipper;
import it.tukano.xml.XmlDoc;
import it.tukano.xml.XmlDoc.XmlNode;
import java.awt.Component;
import java.awt.Rectangle;
import java.io.StringReader;
import javax.swing.JPanel;

/**
 * TODO: delete this
 * @author utente3
 */
public class OdgLayoutPanel extends JPanel {
    /* default serial version uid*/
    private static final long serialVersionUID = 0;

    private static int cmToPoints(String value) {
        value.replace("cm", "");
        double cm = Double.parseDouble(value);
        cm *= 0.035;
        return (int) Math.round(cm);
    }

    private final MapExt<String, Rectangle> boundsMap;
    private final MapExt<String, Component> compMap = new HashMapExt<String, Component>();

    public OdgLayoutPanel(FileExt odgFile) {
        setLayout(null);
        MapExt<String, Rectangle> bmap = new HashMapExt<String, Rectangle>();
        Zipper zipper = new Zipper(odgFile);
        String content = zipper.getEntryAsText("content.xml", "utf-8");
        XmlDoc doc = XmlDoc.newInstance(new StringReader(content));
        XmlNode drawPage = doc.getRoot().getFirstChild("draw:page");
        for(XmlNode rectNode : drawPage.listChildren("draw:rect", true)) {
            String name = rectNode.getString("draw:name");
            if(name != null && !name.isEmpty()) {
                int width = cmToPoints(rectNode.getString("svg:width"));
                int height = cmToPoints(rectNode.getString("svg:height"));
                int x = cmToPoints(rectNode.getString("svg:x"));
                int y = cmToPoints(rectNode.getString("svg:y"));
                Rectangle r = new Rectangle(x, y, width, height);
                bmap.put(name, r);
            }
        }
        this.boundsMap = bmap;
    }

    @Override
    public void add(Component comp, Object constraints) {
        if(constraints == null) throw new IllegalArgumentException("constraints must be a string");
        if(constraints instanceof String == false) throw new IllegalArgumentException("constraints must be a string");
        String c = (String) constraints;
        Rectangle bounds = boundsMap.get(c);
        if(bounds != null) {
            bounds = (Rectangle) bounds.clone();
            Component old = compMap.get(c);
            if(old != null) remove(old);
            compMap.put(c, comp);
            comp.setBounds(bounds);
            super.add(comp);
        }
    }
}
